<template>
  <div class="check-in-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>入住登记</span>
        </div>
      </template>

      <el-form
        ref="checkInFormRef"
        :model="checkInOrder"
        :rules="rules"
        label-width="120px"
        class="check-in-form"
      >
        <!-- 入住子单列表 -->
        <div
          v-for="(subOrder, index) in checkInOrder.subOrders"
          :key="index"
          class="sub-order-item"
        >
          <div class="sub-order-header">
            <h3>
              房间 {{ subOrder.room.roomNumber }}
              <span class="room-type">
                ({{
                  getRoomTypeInfo(subOrder.room.roomTypeId)?.typeName ||
                  "未知类型"
                }})
              </span>
            </h3>
          </div>

          <!-- 入住信息 -->
          <div class="date-picker-row">
            <el-form-item
              :label="'入住日期'"
              :prop="'subOrders.' + index + '.checkInDate'"
              :rules="[
                { required: true, message: '请选择入住日期', trigger: 'change' }
              ]"
            >
              <el-date-picker
                v-model="subOrder.checkInDate"
                type="date"
                placeholder="选择入住日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                @change="handleDateChange(index)"
              />
            </el-form-item>

            <el-form-item
              :label="'离店日期'"
              :prop="'subOrders.' + index + '.checkOutDate'"
              :rules="[
                { required: true, message: '请选择离店日期', trigger: 'change' }
              ]"
            >
              <el-date-picker
                v-model="subOrder.checkOutDate"
                type="date"
                placeholder="选择离店日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                @change="handleDateChange(index)"
              />
            </el-form-item>

            <el-form-item label="住店时长">
              <span class="stay-duration">{{
                calculateStayDuration(
                  subOrder.checkInDate,
                  subOrder.checkOutDate
                )
              }}</span>
            </el-form-item>
          </div>

          <!-- 入住人员信息 -->
          <div class="customers-section">
            <div class="section-header">
              <h4>入住人员信息</h4>
              <el-button type="primary" @click="addCustomer(index)"
                >添加入住人</el-button
              >
            </div>

            <div
              v-for="(customer, cIndex) in subOrder.customers"
              :key="cIndex"
              class="customer-item"
            >
              <el-form-item
                :label="'姓名'"
                :prop="'subOrders.' + index + '.customers.' + cIndex + '.name'"
                :rules="[
                  { required: true, message: '请输入姓名', trigger: 'blur' }
                ]"
              >
                <el-input v-model="customer.name" placeholder="请输入姓名" />
              </el-form-item>

              <el-form-item
                :label="'身份证号'"
                :prop="
                  'subOrders.' + index + '.customers.' + cIndex + '.idCard'
                "
                :rules="[
                  { required: true, message: '请输入身份证号', trigger: 'blur' }
                ]"
              >
                <el-input
                  v-model="customer.idCard"
                  placeholder="请输入身份证号"
                />
              </el-form-item>

              <el-form-item
                :label="'手机号'"
                :prop="'subOrders.' + index + '.customers.' + cIndex + '.phone'"
              >
                <el-input v-model="customer.phone" placeholder="请输入手机号" />
              </el-form-item>

              <el-button
                v-if="subOrder.customers.length > 1"
                type="danger"
                @click="removeCustomer(index, cIndex)"
              >
                删除
              </el-button>
            </div>
          </div>

          <!-- 账单信息 -->
          <div class="bill-section">
            <h4>账单信息</h4>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="房费">
                ¥{{ subOrder.bill.rate }}
              </el-descriptions-item>
              <el-descriptions-item label="押金">
                <el-input-number
                  v-model="subOrder.bill.deposit"
                  :min="0"
                  :precision="2"
                  :step="50"
                  @change="handleDepositChange(index)"
                />
              </el-descriptions-item>
              <el-descriptions-item label="总计">
                ¥{{ subOrder.bill.total }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-footer">
          <div class="total-amount">
            <span class="label">需缴费金额：</span>
            <span class="amount">¥{{ checkInOrder.totalAmount }}</span>
          </div>
          <div class="buttons">
            <el-button type="danger" @click="handleCancel">取消登记</el-button>
            <el-button
              type="primary"
              :disabled="
                !checkInOrder.subOrders || checkInOrder.subOrders.length === 0
              "
              @click="submitForm"
            >
              提交入住
            </el-button>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  startCheckIn,
  refreshCheckIn,
  type CheckInOrder,
  type CheckInSubOrder,
  type Customer,
  type Bill,
  updateCheckIn,
  terminateCheckIn,
  createCheckInPayment
} from "@/api/checkIn";
import { getRoomList, type Room, RoomStatus } from "@/api/room";
import { getRoomTypeList, type RoomType } from "@/api/room";

const route = useRoute();
const router = useRouter();
const checkInFormRef = ref<FormInstance>();

// 入住单数据
const checkInOrder = ref<CheckInOrder>({
  status: "PENDING",
  totalAmount: 0,
  subOrders: []
});

// 表单验证规则
const rules = ref<FormRules>({
  // 可以在这里添加更多的验证规则
});

// 房间类型列表
const roomTypes = ref<RoomType[]>([]);

// 获取房间类型信息
const getRoomTypeInfo = (typeId: number) => {
  return roomTypes.value.find(type => type.typeId === typeId);
};

// 初始化入住单
const initCheckInOrder = async () => {
  const roomNumbers = route.query.roomNumbers as string;
  if (roomNumbers) {
    // 从房间管理页面跳转过来的情况
    const numbers = roomNumbers.split(",");

    try {
      // 获取完整的房间列表
      const { data: roomList } = await getRoomList();
      // 过滤出选中的房间，并确保所有必要信息都存在
      const rooms = roomList.filter(
        room =>
          numbers.includes(room.roomNumber) &&
          room.roomId &&
          room.roomTypeId &&
          room.status === RoomStatus.AVALIABLE
      );

      if (rooms.length === 0) {
        ElMessage.error("未找到有效的房间信息");
        return;
      }

      if (rooms.length !== numbers.length) {
        ElMessage.warning("部分房间信息无效或不可用");
      }

      // 设置默认的入住日期（今天）和离店日期（明天）
      const today = new Date();
      const tomorrow = new Date(today);
      tomorrow.setDate(tomorrow.getDate() + 1);

      // 创建初始入住单
      const initialCheckInOrder: CheckInOrder = {
        status: null,
        totalAmount: 0,
        subOrders: rooms.map(room => ({
          checkInDate: today,
          checkOutDate: tomorrow,
          room: {
            roomId: room.roomId,
            roomTypeId: room.roomTypeId,
            roomNumber: room.roomNumber
          },
          customers: [
            {
              name: "",
              idCard: "",
              phone: ""
            }
          ],
          bill: {
            rate: 0,
            deposit: 0,
            total: 0
          }
        }))
      };

      try {
        // 调用后端 API 开始登记
        const response = await startCheckIn(initialCheckInOrder);

        // 检查响应状态
        console.log("res展示", response);
        if (response === 200) {
          // 使用后端返回的数据更新表单
          checkInOrder.value = response.data;
          console.log("入住单初始化成功:", checkInOrder.value);
        } else {
          ElMessage.warning("当前有尚未完成的登记入住，请完成后再创建");
          try {
            const response = await refreshCheckIn();
            if (response.code === 200) {
              // 有正在办理的入住登记，使用返回的数据渲染表单
              checkInOrder.value = response.data;
            } else {
              // 没有正在办理的入住登记
              ElMessage.warning(response.msg);
              // 可以选择跳转回房间列表页
              // router.push("/room/detail");
            }
          } catch (error) {
            console.error("获取当前入住登记表单失败:", error);
            ElMessage.error("获取当前入住登记表单失败");
            // 可以选择跳转回房间列表页
            router.push("/room/list");
          }
        }
      } catch (apiError) {
        console.error("调用入住API失败:", apiError);
        // API调用失败时，使用本地创建的数据
        checkInOrder.value = initialCheckInOrder;
        ElMessage.warning("连接服务器失败，将使用默认数据");
      }
    } catch (error) {
      ElMessage.error("获取房间信息失败");
    }
  } else {
    // 直接访问入住登记页面的情况
    try {
      const response = await refreshCheckIn();
      if (response.code === 200) {
        // 有正在办理的入住登记，使用返回的数据渲染表单
        checkInOrder.value = response.data;
      } else {
        // 没有正在办理的入住登记
        ElMessage.warning(response.msg);
        // 可以选择跳转回房间列表页
        // router.push("/room/detail");
      }
    } catch (error) {
      console.error("获取当前入住登记表单失败:", error);
      ElMessage.error("获取当前入住登记表单失败");
      // 可以选择跳转回房间列表页
      router.push("/room/list");
    }
  }
};

// 添加入住人
const addCustomer = (subOrderIndex: number) => {
  const newCustomer: Customer = {
    name: "",
    idCard: "",
    phone: ""
  };
  checkInOrder.value.subOrders[subOrderIndex].customers.push(newCustomer);
};

// 删除入住人
const removeCustomer = (subOrderIndex: number, customerIndex: number) => {
  checkInOrder.value.subOrders[subOrderIndex].customers.splice(
    customerIndex,
    1
  );
};

// 处理日期变化
const handleDateChange = async (subOrderIndex: number) => {
  console.log("更新前:", {
    checkInDate: checkInOrder.value.subOrders[subOrderIndex].checkInDate,
    checkOutDate: checkInOrder.value.subOrders[subOrderIndex].checkOutDate,
    bill: checkInOrder.value.subOrders[subOrderIndex].bill
  });

  try {
    const response = await updateCheckIn(checkInOrder.value);
    if (response && response.data) {
      checkInOrder.value = response.data;
      console.log("更新后:", {
        checkInDate: checkInOrder.value.subOrders[subOrderIndex].checkInDate,
        checkOutDate: checkInOrder.value.subOrders[subOrderIndex].checkOutDate,
        bill: checkInOrder.value.subOrders[subOrderIndex].bill
      });
    }
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新账单失败");
  }
};

// 押金变化
const handleDepositChange = async (subOrderIndex: number) => {
  try {
    const response = await updateCheckIn(checkInOrder.value);
    if (response.code === 200) {
      checkInOrder.value = response.data;
    } else {
      ElMessage.error(response.msg);
    }
  } catch (error) {
    ElMessage.error("更新账单失败");
  }
};

// 计算住店时长
const calculateStayDuration = (
  checkInDate: string | null,
  checkOutDate: string | null
) => {
  if (!checkInDate || !checkOutDate) return "请选择日期";

  const start = new Date(checkInDate);
  const end = new Date(checkOutDate);
  const diffTime = Math.abs(end.getTime() - start.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return `${diffDays} 晚`;
};

// 提交表单
const submitForm = async () => {
  if (!checkInFormRef.value) return;

  // 检查是否有入住单
  if (
    !checkInOrder.value.subOrders ||
    checkInOrder.value.subOrders.length === 0
  ) {
    ElMessage.warning("当前没有可提交的入住单");
    return;
  }

  await checkInFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const paymentResponse = await createCheckInPayment();
        if (paymentResponse.code !== 200) {
          ElMessage.error(paymentResponse.msg || "创建支付失败");
          return;
        }
        ElMessage.success("入住登记成功");
        router.push("/room/detail");
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败，请稍后重试");
      }
    }
  });
};

// 初始化时获取房间类型列表
const initRoomTypes = async () => {
  try {
    const response = await getRoomTypeList();
    if (response && response.data) {
      roomTypes.value = response.data;
    }
  } catch (error) {
    console.error("获取房间类型列表失败:", error);
  }
};

// 取消登记
const handleCancel = () => {
  ElMessageBox.confirm(
    "确定要取消登记吗？取消后所有已填写的信息将丢失。",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      try {
        await terminateCheckIn();
        ElMessage.success("已取消登记");
        router.push("/room/detail");
      } catch (error) {
        console.error("取消登记失败:", error);
        ElMessage.error("取消登记失败");
      }
    })
    .catch(() => {
      // 用户点击取消，不做任何操作
    });
};

onMounted(async () => {
  await initRoomTypes();
  await initCheckInOrder();
});
</script>

<style scoped>
.check-in-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sub-order-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 30px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.sub-order-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.sub-order-header h3 {
  font-size: 18px;
  color: #303133;
  margin: 0;
}

.customers-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px dashed #dcdfe6;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h4 {
  font-size: 16px;
  color: #303133;
  margin: 0;
}

.customer-item {
  border: 1px dashed #dcdfe6;
  padding: 20px;
  margin-bottom: 20px;
  position: relative;
}

.bill-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px dashed #dcdfe6;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
}

.total-amount {
  margin-bottom: 20px;
  font-size: 18px;
}

.total-amount .label {
  color: #606266;
}

.total-amount .amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 24px;
  margin-left: 10px;
}

.buttons {
  margin-top: 20px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.date-picker-row {
  display: flex;
  gap: 20px;
}

.date-picker-row .el-form-item {
  flex: 1;
  margin-right: 0;
}

.stay-duration {
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
}

.room-type {
  font-size: 14px;
  color: #909399;
  margin-left: 8px;
  font-weight: normal;
}
</style>
